extends Control

@onready var grid_container: GridContainer = %GridContainer
@onready var attempts_label: Label = %AttemptsLabel
# 游戏配置
const TOTAL_PAIRS := 6  # 6对卡牌 = 12张
const MAX_ATTEMPTS := 5  # 5次翻对机会
const filp_card_tscn = preload("res://scenes/vfx/翻转卡牌/flip_card.tscn")
# 卡牌数据
var card_values := ["A", "B", "C", "D", "E", "F"]
var cards := []
var flipped_cards := []
var matched_pairs := 0
var attempts_left := MAX_ATTEMPTS
var rewards := {
	"A": {"name": "金币", "amount": 200, "des": "金币\n200"},
	"B": {"name": "金币", "amount": 400, "des": "金币\n400"},
	"C": {"name": "技能", "amount": 1, "des": "随机技能"},
	"D": {"name": "金币", "amount": 600, "des": "金币\n600"},
	"E": {"name": "装备", "amount": 2, "des": "2级装备"},
	"F": {"name": "装备", "amount": 3, "des": "3级装备"}
}
func _ready() -> void:
	setup_game()
	
func setup_game() -> void:
	get_tree().paused = true
	# 重置游戏状态
	cards.clear()
	flipped_cards.clear()
	matched_pairs = 0
	attempts_left = MAX_ATTEMPTS
	attempts_label.text = "剩余次数：%s" % attempts_left
	
	# 清空网格
	for child in grid_container.get_children():
		child.queue_free()
		
	# 创建卡牌数据（6对）
	var card_data = []
	for value in card_values:
		card_data.append(value)
		card_data.append(value)
	
	# 打乱卡牌顺序
	card_data.shuffle()
	
	# 创建卡牌UI
	for i in range(card_data.size()):
		var flip_card_ins = filp_card_tscn.instantiate()
		flip_card_ins.type = card_data.get(i)
		grid_container.add_child(flip_card_ins)
		flip_card_ins.label.set_text(rewards.get(str(card_data.get(i)))["des"])
		flip_card_ins.flip.connect(on_flip)
		flip_card_ins.father = self


## 有两个时候翻面的时候，需要重新判断
func on_flip(flip_card: FlipPanel):
	## 防止点击对一个点击太快
	if flipped_cards.has(flip_card) or attempts_left <= 0:
		return

	if flipped_cards.size() < 1:
		flipped_cards.push_back(flip_card)	
		return
	attempts_left -= 1
	attempts_label.text = "剩余次数：%s" % attempts_left
	var first: FlipPanel = flipped_cards.pop_back()
	var second: FlipPanel = flip_card
	await second.animation_player.animation_finished
	## 如果类型相同获得奖励
	if first.type == second.type:
		var reward = rewards[first.type]
		match reward["name"]:
			"金币":
				Utils.set_player_stats_value("gold", reward["amount"])
			"技能":
				RaffleManager._get_skill_reward(1)
			"装备":
				RaffleManager._get_equipment_reward(reward["amount"])
				
		first.burning_anim()
		second.burning_anim()
	else:
		first.flip_back_anim()
		second.flip_back_anim()
	
	if attempts_left <= 0:
		await get_tree().create_timer(0.5).timeout
		get_tree().paused = false
		self.queue_free()
	
		
